/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Formularios;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author FRANCISCO
 */
public class nuevaventa extends javax.swing.JFrame {

    /**
     * Creates new form nuevaventa
     */
    public nuevaventa() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        actualizartabla2();
        txtcantidad.setEditable(false);
        txtproducto.setEditable(false);
        txttotal.setEditable(false);
        btnadd.setEnabled(false);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        chkAvisar = new javax.swing.JCheckBox();
        btnadd = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtproducto = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtcantidad = new javax.swing.JTextField();
        btncanselar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        grilla = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        txttotal = new javax.swing.JTextField();
        btnnue = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        grilla2 = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("NUEVA VENTA");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        chkAvisar.setSelected(true);
        chkAvisar.setText("Avisar critico");
        getContentPane().add(chkAvisar, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 480, -1, -1));

        btnadd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/new.png"))); // NOI18N
        btnadd.setText("AGREGAR");
        btnadd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnaddActionPerformed(evt);
            }
        });
        getContentPane().add(btnadd, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 50, 220, 70));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("PRODUCTO");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 140, 60));

        txtproducto.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        getContentPane().add(txtproducto, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 50, 270, 60));

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("CANTIDAD");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, -1, -1));

        txtcantidad.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        txtcantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtcantidadKeyTyped(evt);
            }
        });
        getContentPane().add(txtcantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 150, 50));

        btncanselar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/delete.png"))); // NOI18N
        btncanselar.setText("CANCELAR");
        btncanselar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncanselarActionPerformed(evt);
            }
        });
        getContentPane().add(btncanselar, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 150, 140, 50));

        jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        grilla.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        grilla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "NOMBRE", "PRECIO", "STOCK"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(grilla);
        grilla.getColumnModel().getColumn(0).setResizable(false);
        grilla.getColumnModel().getColumn(1).setResizable(false);
        grilla.getColumnModel().getColumn(2).setResizable(false);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 270, 550, 220));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("TOTAL ESTA VENTA");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 370, 220, 20));

        txttotal.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        getContentPane().add(txttotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 410, 190, 40));

        btnnue.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/key_enter.png"))); // NOI18N
        btnnue.setText("NUEVA VENTA");
        btnnue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnueActionPerformed(evt);
            }
        });
        getContentPane().add(btnnue, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 250, 160, 80));

        grilla2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Precio", "Stock"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(grilla2);
        grilla2.getColumnModel().getColumn(0).setResizable(false);
        grilla2.getColumnModel().getColumn(1).setResizable(false);
        grilla2.getColumnModel().getColumn(2).setResizable(false);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 30, 230, 440));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/energia_azul-1024x768.jpg"))); // NOI18N
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 520));

        pack();
    }// </editor-fold>//GEN-END:initComponents


    private void btncanselarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncanselarActionPerformed
        Plataforma pla = new Plataforma();
        pla.setVisible(true);
        dispose();
    }//GEN-LAST:event_btncanselarActionPerformed

    private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnaddActionPerformed
//      s.execute("call Total ('"+txtproducto.getText()+"','"+txtcantidad.getText()+"');");
        try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                ResultSet rs = s.executeQuery("call Total ('"+txtproducto.getText()+"','"+txtcantidad.getText()+"');");
                actualizartabla2();
               txtcantidad.setText("");
               txtproducto.setText("");
               
               
              
            DefaultTableModel modelo = new DefaultTableModel();

            this.grilla.setModel(modelo);
            ResultSetMetaData rsMd = rs.getMetaData();
            int cantidadColumnas = rsMd.getColumnCount();

            for (int i = 1; i <= cantidadColumnas; i++) {
                modelo.addColumn(rsMd.getColumnLabel(i));
            }
            
            while (rs.next()) {
                Object[] fila = new Object[cantidadColumnas];
                for (int j = 0; j < cantidadColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                    
                    
                    
                    
                   
                    if(j==2){
                       txttotal.setText(rs.getObject(j).toString());
                       
                    }
                        System.out.println(j);
                }
                modelo.addRow(fila);
            }}
            }   catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
    
          actualizartabla();
    }//GEN-LAST:event_btnaddActionPerformed

    private void btnnueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnueActionPerformed
        nuevaventa();
         txtcantidad.setEditable(true);
        txtproducto.setEditable(true);
        txttotal.setEditable(false);
        btnadd.setEnabled(true);
        
    }//GEN-LAST:event_btnnueActionPerformed

    private void txtcantidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcantidadKeyTyped
        if(!Character.isDigit(evt.getKeyChar())){
    evt.consume();
    }//GEN-LAST:event_txtcantidadKeyTyped
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(nuevaventa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(nuevaventa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(nuevaventa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(nuevaventa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new nuevaventa().setVisible(true);
            }
        });
    }
    
    public void actualizartabla(){
    try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                ResultSet rs = s.executeQuery("select * from venta");
                
               
              
            DefaultTableModel modelo = new DefaultTableModel();

            this.grilla.setModel(modelo);
            ResultSetMetaData rsMd = rs.getMetaData();
            int cantidadColumnas = rsMd.getColumnCount();
rs.getMetaData();
            for (int i = 1; i <= cantidadColumnas; i++) {
                modelo.addColumn(rsMd.getColumnLabel(i));
            }
            
            while (rs.next()) {
                Object[] fila = new Object[cantidadColumnas];
                for (int j = 0; j < cantidadColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                    
                    
                   
                    
                        System.out.println(j);
                }
                modelo.addRow(fila);
            }
            } }  catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
    
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnadd;
    private javax.swing.JButton btncanselar;
    private javax.swing.JButton btnnue;
    private javax.swing.JCheckBox chkAvisar;
    private javax.swing.JTable grilla;
    private javax.swing.JTable grilla2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField txtcantidad;
    private javax.swing.JTextField txtproducto;
    private javax.swing.JTextField txttotal;
    // End of variables declaration//GEN-END:variables

    private void nuevaventa() {
         
       try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                s.execute("call NuevaVenta()");
                
                JOptionPane.showMessageDialog(this,"nueva venta creada inserte productos","venta", 1);
                
             
            }
            }   catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
    
         
    }
    
    
    public void actualizartabla2(){
    try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/pasteleria1211","root", "12345")) {
               
                Statement s = conexion.createStatement();

                ResultSet rs = s.executeQuery("select * from producto ");
                
               
              
            DefaultTableModel modelo = new DefaultTableModel();

            this.grilla2.setModel(modelo);
            ResultSetMetaData rsMd = rs.getMetaData();
            int cantidadColumnas = rsMd.getColumnCount();
rs.getMetaData();
            for (int i = 1; i <= cantidadColumnas; i++) {
                modelo.addColumn(rsMd.getColumnLabel(i));
            }
            
            while (rs.next()) {
                Object[] fila = new Object[cantidadColumnas];
                for (int j = 0; j < cantidadColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                    
                    if(j == 2){
                        int stock = Integer.parseInt(fila[j].toString());
                        
                        final int CRITICO = getCritico();
                        
                        if(stock <= CRITICO){
                            //
                            
                            if(this.chkAvisar.isSelected()){
                                System.out.println("CRITICO de : "+fila[j-2]);
                            }
                            
                        }
                        
                    }
                   
                    
                        System.out.println(j);
                }
                modelo.addRow(fila);
            }
            } }  catch (SQLException s) {
                      JOptionPane.showMessageDialog(null, s, "no se encontro al usuario" + s, JOptionPane.ERROR_MESSAGE);
             }
    
    }

    private int getCritico() {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return 5;
    }
    }

